package com.xiaoerkeji.eshop;


import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.drawable.Icon;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.widget.Toast;

import com.lt.app.IntentHelper;
import com.lt.system.DynamicShortcutHelper;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.smtt.export.external.interfaces.ConsoleMessage;
import com.tencent.smtt.export.external.interfaces.JsResult;
import com.tencent.smtt.export.external.interfaces.PermissionRequest;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.xiaoerkeji.eshop.databinding.ActMainBinding;
import com.xiaoerkeji.eshop.listener.MyDialogListener;
import com.xiaoerkeji.eshop.plug.TopBarHelper;
import com.xiaoerkeji.eshop.update.AppUpdater;
import com.xiaoerkeji.eshop.utils.ClipboardUtils;
import com.xiaoerkeji.eshop.utils.ComUtils;
import com.xiaoerkeji.eshop.utils.CommandUtils;
import com.xiaoerkeji.eshop.utils.DynamicShortcutManager;
import com.xiaoerkeji.eshop.utils.ScanActivity;
import com.xiaoerkeji.eshop.utils.SharedPrefUtil;

import java.util.HashMap;
import java.util.Map;


public class MainActivity extends BaseActivityMy
{
    // IWXAPI 是第三方app和微信通信的openApi接口
    private IWXAPI api;

    private AppUpdater appUpdater;

    public static final int SCAN_REQUEST_CODE = 100; // 改为 public
    private ActMainBinding binding;


    @Override
    protected void receiveMessage(Message msg)
    {

    }

    @Override
    protected View getLayoutView()
    {
        binding = ActMainBinding.inflate(getLayoutInflater());
        return binding.getRoot();
    }

    @Override
    protected void init()
    {
        binding.tvBarTitle.setText("小二");
        binding.ivBarLeft.setOnClickListener(onClick);
        binding.ivBarRight.setOnClickListener(onClick);
        initWebView();
        handleIntent(getIntent());
        addCustomShortcutTest();
    }


//    @Override
//    protected void onCreate(Bundle savedInstanceState)
//    {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.act_main);
//        //检查自动更新
//        appUpdater = new AppUpdater(this, this, CommandUtils.AUTO_UPDATE_URL);
//        appUpdater.checkForUpdates();
////        Button button = findViewById(R.id.button_first);
////        button.setOnClickListener(this);
////
////        regToWx();
//        // 处理传入的Intent
//        handleIntent(getIntent());
//    }

    ;

    private void handleIntent(Intent intent)
    {
        if (intent == null || intent.getAction() == null)
        {
            return;
        }
        log("handleIntent:" + intent.getAction());
        if (Intent.ACTION_VIEW.equals(intent.getAction()))
        {
            Uri uri = intent.getData();
            if (uri != null)
            {
                /*
                    接受微信传过来的参数
                 */
                if (("http".equals(uri.getScheme()))
                        || ("https".equals(uri.getScheme())))
                {
                    binding.webView.loadUrl(uri.toString());
                }
            }
        }
        Bundle extras = getIntent().getExtras();
        if (extras == null)
        {
            return;
        }
        String action = extras.getString("xe_action", "");
        if ("shortcut".equals(action))
        {
            String url = extras.getString("url", "");
            if (!TextUtils.isEmpty(url))
            {
                binding.webView.loadUrl(url);
            }
        }


//        Uri data = intent.getData();
//        if (data != null)
//        {
//            // 解析URI参数
//            String scheme = data.getScheme();   // "myapp"
//            String host = data.getHost();       // "example.com" (如果有)
//            String path = data.getPath();       // "/open" (如果有)
//            // 获取查询参数
//            String param1 = data.getQueryParameter("param1");
//            String param2 = data.getQueryParameter("param2");
//            // 根据URI跳转到对应的页面或执行相应操作
////                navigateBasedOnDeepLink(data);
//        }
    }


    private void initWebView()
    {
        WebSettings webSetting = binding.webView.getSettings();
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(false);
        // webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true);
        // webSetting.setDatabaseEnabled(true);
        // 启用JavaScript
        webSetting.setDomStorageEnabled(true);
        webSetting.setJavaScriptEnabled(true);
        webSetting.setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        webSetting.setMediaPlaybackRequiresUserGesture(false);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        webSetting.setAppCachePath(this.getDir("appcache", 0).getPath());
        webSetting.setDatabasePath(this.getDir("databases", 0).getPath());
        webSetting.setGeolocationDatabasePath(this.getDir("geolocation", 0)
                .getPath());
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        // webSetting.setPreFectch(true);

        // 缓存模式说明:
        // LOAD_CACHE_ONLY: 不使用网络，只读取本地缓存数据
        // LOAD_NO_CACHE: 不使用缓存，只从网络获取数据.
        // LOAD_DEFAULT: （默认）根据cache-control决定是否从网络上取数据。
        // LOAD_CACHE_ELSE_NETWORK，只要本地有，无论是否过期，或者no-cache，都使用缓存中的数据。
        webSetting.setCacheMode(WebSettings.LOAD_DEFAULT);
        // 注册JS接口回调
        binding.webView.addJavascriptInterface(new WebAppInterface(this), "Android");

        // 设置WebViewClient
        binding.webView.setWebViewClient(mWebViewClient);

        binding.webView.setWebChromeClient(mWebChromeClient);


    }

    // JS回调的接口
    public class WebAppInterface
    {

        WebAppInterface(Context context)
        {

        }

        @JavascriptInterface
        public String getDeviceInfo()
        {
            return Build.MODEL;
        }

        @JavascriptInterface
        public void writeSharedPreference(String key, String value)
        {
            SharedPrefUtil.saveString(getApplicationContext(), key, value);
        }

        @JavascriptInterface
        public String readSharedPreference(String key)
        {
            return SharedPrefUtil.getString(getApplicationContext(), key, "");
        }

        @JavascriptInterface
        public void startScan()
        {
            // 启动扫码 Activity
            runOnUiThread(MainActivity.this::scan);
        }
    }


    private final WebViewClient mWebViewClient = new WebViewClient()
    {
        @Override
        public boolean shouldOverrideUrlLoading(WebView webView, String url)
        {
            WebView.HitTestResult hit = webView.getHitTestResult();
            //hit.getExtra()为null或者hit.getType() == 0都表示即将加载的URL会发生重定向，需要做拦截处理
            if (TextUtils.isEmpty(hit.getExtra()) || hit.getType() == 0)
            {
                //通过判断开头协议就可解决大部分重定向问题了，有另外的需求可以在此判断下操作
                log("重定向: " + hit.getType() + " && EXTRA（）" + hit.getExtra() + "------");
                log("重定向:GetURL: " + webView.getUrl() + "\n" + "getOriginalUrl()" + webView.getOriginalUrl());
                log("重定向:URL: " + url);
            }
            if (!handleUrlLoading(url))
            {
                webView.loadUrl(url);
                //返回false表示此url默认由系统处理,url未加载完成，会继续往下走
                return false;
            }
            return true;
        }

        @Override
        public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, SslError sslError)
        {
            if (sslError.getPrimaryError() == android.net.http.SslError.SSL_INVALID)
            {// 校验过程遇到了bug
                sslErrorHandler.proceed(); // 接受所有网站的证书
            } else
            {
                sslErrorHandler.cancel();
            }
            super.onReceivedSslError(webView, sslErrorHandler, sslError);
        }

        // 开始加载网页时要做的工作
        @Override
        public void onPageStarted(WebView webView, String s, Bitmap bitmap)
        {
            super.onPageStarted(webView, s, bitmap);
        }
    };

    private final WebChromeClient mWebChromeClient = new WebChromeClient()
    {
        @Override
        public void onProgressChanged(WebView webView, int i)
        {
            if (i >= 100)
            {
                binding.progressBar.setVisibility(View.GONE);
            } else
            {
                if (binding.progressBar.getVisibility() != View.VISIBLE)
                {
                    binding.progressBar.setVisibility(View.VISIBLE);
                }
                binding.progressBar.setProgress(i);
            }
            super.onProgressChanged(webView, i);
        }

        //获得网页的标题
        @Override
        public void onReceivedTitle(WebView webView, String title)
        {
            if (!TextUtils.isEmpty(title))
            {
                binding.tvBarTitle.setText(title);
            }
            super.onReceivedTitle(webView, title);
        }

        @Override
        public void onReceivedIcon(WebView webView, Bitmap bitmap)
        {
            super.onReceivedIcon(webView, bitmap);
        }

        @Override
        public void onPermissionRequest(final PermissionRequest request)
        {
            // 允许权限请求
            request.grant(request.getResources());
            request.getOrigin();
        }

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage)
        {
            return super.onConsoleMessage(consoleMessage);
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result)
        {
            result.confirm();
            return true;
        }
    };


    private void updateView()
    {
        if (TextUtils.isEmpty(binding.webView.getUrl()))
        {

        }
    }

    // 处理URL重定向，true表示已处理，false表示需要浏览器重定向
    private boolean handleUrlLoading(String url)
    {
        if (TextUtils.isEmpty(url))
        {
            return true;
        }
        // 拦截电话链接
        if (url.startsWith("tel:"))
        {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_DIAL);
            intent.setData(Uri.parse(url));
            startActivity(intent);
            return true;
        }
        // 拦截邮件链接
        if (url.startsWith("mailto:"))
        {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_SENDTO);
            intent.setData(Uri.parse(url));
            startActivity(intent);
            return true;
        }
        // 拦截地图链接
        if (url.startsWith("geo:"))
        {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(url));
            startActivity(intent);
            return true;
        }
        // 处理自定义 Scheme
        if (url.startsWith("myapp://"))
        {
            return true;
        }
        return !ComUtils.isUrl(url);
    }


    @Override
    protected void onNewIntent(Intent intent)
    {
        super.onNewIntent(intent);
        handleIntent(getIntent());
    }

    /**
     * 重写返回键事件，弹出退出确认对话框
     */
    @Override
    public void onBackPressed()
    {
        back();
    }


    //返回键拦截
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK)
        {
            //自定义返回键行为
            if (binding.webView.canGoBack())
            {
                binding.webView.goBack();
                return true; // 表示事件已被处理，不再继续传递
            }
        }
        return super.onKeyDown(keyCode, event); // 对于其他按键，调用父类的处理方法
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        getWindow().getDecorView().post(new Runnable()
        {
            @Override
            public void run()
            {
                // 在这里读取剪贴板
                String txt = ClipboardUtils.getClipboardContent(getApplicationContext());
                //Toast.makeText(MainActivity.this, txt, Toast.LENGTH_LONG).show();
                // 执行JS
//                webView.evaluateJavascript("initApp("+txt+")", null);
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SCAN_REQUEST_CODE && resultCode == RESULT_OK)
        {
            String scanResult = data.getStringExtra("SCAN_RESULT");
            if (TextUtils.isEmpty(scanResult))
            {
                showToast(R.string.invalid_url);
                return;
            }
            if (ComUtils.isUrl(scanResult))
            {
                binding.webView.loadUrl(scanResult);
            } else
            {
                showToast(R.string.invalid_url);
            }
//            binding.webView.evaluateJavascript("onScanResult('" + scanResult + "')", null);
        }
    }

    private final View.OnClickListener onClick = new View.OnClickListener()
    {
        @SuppressLint("NonConstantResourceId")
        @Override
        public void onClick(View v)
        {
            switch (v.getId())
            {
                case R.id.iv_bar_left:
                    back();
                    break;
                case R.id.iv_bar_right:
                    scan();
                    break;
            }
            if (v.getId() == R.id.button_first)
            {
                Log.d("1111", "1111111");
//            if (!api.isWXAppInstalled()) {
//                Toast.makeText(this, "未安装微信", Toast.LENGTH_SHORT).show();
//                return;
//            }
                SendAuth.Req req = new SendAuth.Req();
                req.scope = "snsapi_userinfo";
                req.state = "wechat_login";
                api.sendReq(req);

            }
        }
    };


    private void regToWx()
    {
        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        api = WXAPIFactory.createWXAPI(this, CommandUtils.APP_ID, true);

        // 将应用的appId注册到微信
        api.registerApp(CommandUtils.APP_ID);


        //建议动态监听微信启动广播进行注册到微信
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        {
            this.registerReceiver(new BroadcastReceiver()
            {
                @Override
                public void onReceive(Context context, Intent intent)
                {

                    // 将该app注册到微信
                    api.registerApp(CommandUtils.APP_ID);
                }
            }, new IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP), this.RECEIVER_EXPORTED);
        }

    }

    private void back()
    {
        if (binding.webView.canGoBack())
        {
            binding.webView.goBack();
        } else
        {
            showDialog("是否确定退出应用？", R.string.sure, R.string.cancel, new MyDialogListener()
            {
                @Override
                public void onClickLeftButton()
                {
                    closeAllDialog();
                    finish();
                }
            });
        }
    }

    private void scan()
    {
        Intent intent = new Intent(MainActivity.this, ScanActivity.class);
        startActivityForResult(intent, SCAN_REQUEST_CODE);
    }


    private void addCustomShortcutTest()
    {
        HashMap<String, Object> params = new HashMap<>();
        params.put("xe_action", "shortcut");
        params.put("url", "https://www.163.com");
        DynamicShortcutHelper.getInstance().addCustomShortcut(
                this,
                String.valueOf(System.currentTimeMillis()),
                "测试",
                "打开网址",
                Icon.createWithResource(MainActivity.this, R.mipmap.applogo),
                MainActivity.class,
                params
        );
    }
}